package com.zhangyj.impl.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zhangyj.dao.ProgramDao;
import com.zhangyj.db.DBUtil;
import com.zhangyj.entitis.Role;

public class ProgramDaoImpl implements ProgramDao {
	public String getProgramResource(int programeid, int userid) throws SQLException {
		StringBuilder sql = new StringBuilder();
		sql.append("select l.resource from programlist l");
		sql.append(" inner join programrole p on l.programid= p.programid");
		sql.append(" inner join userrole r on p.roleid=r.roleid");
		sql.append(" where r.userid=? and p.programid=?");
		Connection conn = null;
		String resource = null;
		try {
			conn = DBUtil.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql.toString());
			ps.setInt(1, userid);
			ps.setInt(2, programeid);
			ResultSet rst = ps.executeQuery();
			if (rst.next()) {
				resource = rst.getString(1);
			}
			rst.close();
			ps.close();
		} finally {
			if (conn != null) {
				conn.close();
			}
		}
		return resource;
	}

	public List<Role> getProgramRoles(int programeid) throws SQLException {
		StringBuilder sql = new StringBuilder();
		sql.append("select a.roleid, a.rolename,b.permission from roleinfo a");
		sql.append(" left join programrole b on a.roleid=b.roleid and b.programid=?");
		Connection conn = null;
		List<Role> resource = new ArrayList<Role>();
		try {
			conn = DBUtil.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql.toString());
			ps.setInt(1, programeid);
			ResultSet rst = ps.executeQuery();
			while (rst.next()) {
				Role role = new Role();
				role.setRoleid(rst.getInt(1));
				role.setRolename(rst.getString(2));
				role.setOption_permission(rst.getInt(3));
				resource.add(role);
			}
			rst.close();
			ps.close();
		} finally {
			if (conn != null) {
				conn.close();
			}
		}
		return resource;
	}

	public void saveProgramRoles(int programeid, List<Role> roles) throws SQLException {
		try {
			DBUtil.begnTrans();
			Connection conn = DBUtil.getConnection();
			PreparedStatement ps = conn.prepareStatement("delete from programrole where programid=?");
			ps.setInt(1, programeid);
			ps.executeUpdate();
			ps.close();
			ps = conn.prepareStatement("insert into programrole(roleid,permission,programid) values(?,?,?)");
			for (int i = 0; i < roles.size(); i++) {
				Role role = roles.get(i);
				ps.setInt(1, role.getRoleid());
				ps.setInt(2, role.getOption_permission());
				ps.setInt(3, programeid);
				ps.addBatch();
				if (i != 0 && i % 20 == 0) {
					ps.executeBatch();
				}
			}
			ps.executeBatch();
			ps.close();
			DBUtil.commit();
		} catch (SQLException e) {
			DBUtil.rollback();
			throw e;
		} finally {
			DBUtil.close();
		}
	}
}
